package com.le.tester.imooc.oldfairy.coding.collection;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * createTime：2023/4/25 17:35
 * description：LRU:最近最少使用；LFU：最少使用
 */
public class LRUCache<K, V> implements Iterable<K> {

    public static final int MAX = 3;
    LinkedHashMap<K, V> cache = new LinkedHashMap<>();

    public void cache(K key, V value) {
        if (cache.containsKey(key)) {
            cache.remove(key);
        } else if (cache.size() >= MAX) {
            //先进先出的队列
            Iterator<K> iterator = cache.keySet().iterator();
            K next = iterator.next();
            cache.remove(next);
        }
        cache.put(key, value);
    }

    @Override
    public Iterator<K> iterator() {
        return cache.keySet().iterator();
    }

    public static void main(String[] args) {

        LRUCache<String, Integer> lru = new LRUCache<>();

        lru.cache("A", 1);
        lru.cache("B", 2);
        lru.cache("C", 3);

        lru.cache("D", 4);
        lru.cache("C", 10);

        System.out.println("leave<-" + StreamSupport
                .stream(lru.spliterator(), false).map(Object::toString).collect(Collectors.joining("<-")));


    }
}
